import React, { Component } from 'react';
import { Button, Upload, Modal, Steps, Row } from 'antd';
import ImageCrop from './imageCrop';
import PropTypes from 'prop-types';
import ImageEraser from './imageEraser';

export default class ImageSearch extends Component {
	constructor(props) {
		super(props);
		this.reader = new FileReader();
		this.imgRef = React.createRef();
		this.state = {
			visible: false,
			readerLoading: 0,
			current: 0,
			imageData: ''
		};
	}
	componentDidMount() {
		// 进入loading, 加载图片
		this.reader.onloadstart = (e) => {
			this.setState({
				readerLoading: this.state.readerLoading + 1
			});
		};
		this.reader.onloadend = (e) => {
			this.setState({
				readerLoading: this.state.readerLoading - 1,
				imageData: this.reader.result,
				visible: true
			});
		};
	}
	beforeUpload(file) {
		this.reader.readAsDataURL(file);
		return false;
	}
	onCancel() {
		this.setState({
			current: 0,
			visible: false
		});
	}
	onNextStep(imageData) {
		this.setState({
			current: this.state.current + 1,
			imageData: imageData
		});
	}
	onPreStep() {
		this.setState({
			current: this.state.current - 1,
			// 决定上一步是否保留当前步骤的编辑结果
			// imageData: imageData
		});
	}
	render() {
		// 动态改变content内容
		let content;
		switch (this.state.current) {
			case 0:
				content = <ImageCrop imageData={this.state.imageData} onNextStep={this.onNextStep.bind(this)} />;
				break;
			case 1:
				content = (
					<ImageEraser
						imageData={this.state.imageData}
						onPreStep={this.onPreStep.bind(this)}
						onNextStep={this.onNextStep.bind(this)}
					/>
				);
				break;
			case 2:
				// 模拟搜索
				setTimeout(() => {
					this.onNextStep(this.state.imageData)
				}, 1000);
				content = <h1>搜索中...(loading示例)</h1>;
				break;
			case 3:
				content = (
					<div>
						<h1>搜索结果:(结果示例)</h1>
						<img src={this.state.imageData} />
					</div>
				);
				break;
			default:
				break;
		}
		return (
			<div>
				<Upload accept="image/jpeg,image/png" showUploadList={false} beforeUpload={this.beforeUpload.bind(this)}>
					<Button icon="search" loading={this.state.readerLoading > 0}>
						以图搜图
					</Button>
				</Upload>
				<Modal
					title="图片编辑"
					visible={this.state.visible}
					footer={false}
					onCancel={this.onCancel.bind(this)}
					width="800px"
					destroyOnClose
					maskClosable={false}
				>
					{content}
				</Modal>
			</div>
		);
	}
}

ImageSearch.propTypes = {
	onSubmit: PropTypes.func.isRequired
};
